package com.uinnova.product.eam.init;

import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.xss.core.XssCleaner;
import net.dreamlu.mica.xss.core.XssType;
import net.dreamlu.mica.xss.utils.XssUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 如梦的xss拦截库默认会将换行符拦截调，这里重写下放过换行符
 *
 * @author lichong
 * @since 2023/4/7 10:43
 */
@Slf4j
@Configuration
public class XssConfig implements ApplicationRunner {

    public static final XssUtil.HtmlSafeList WHITE_LIST = new XssUtil.HtmlSafeList();
//    public static final Safelist WHITE_LIST = Safelist.basicWithImages();

    @Bean
    public XssCleaner xssCleaner() {
        return new XssCleaner() {

            @Override
            public String clean(String s, String s1, XssType xssType) {
                Document.OutputSettings settings = new Document.OutputSettings()
                        // 1. 转义用最少的规则，没找到关闭的方法
                        .escapeMode(Entities.EscapeMode.xhtml)
                        // 2. 保留换行
                        .prettyPrint(false);
                //对富文本内容进行转义
                //log.info("对富文本内容转义: " + s1);
                s1 = StringEscapeUtils.unescapeHtml(s1);
                //log.info("转义结果: " + s1);
                // 注意会被转义
                String escapedText = Jsoup.clean(s1, "",WHITE_LIST, settings);
                //log.info("处理结果: " + escapedText);
                // 3. 反转义
                return Entities.unescape(escapedText);
            }

            @Override
            public String clean(String html, XssType xssType) {
                Document.OutputSettings settings = new Document.OutputSettings()
                        // 1. 转义用最少的规则，没找到关闭的方法
                        .escapeMode(Entities.EscapeMode.xhtml)
                        // 2. 保留换行
                        .prettyPrint(false);
                //对富文本内容进行转义
                log.info("clean 对富文本内容转义: " + html);
                html = StringEscapeUtils.unescapeHtml(html);
                log.info("clean 转义结果: " + html);
                // 注意会被转义
                String escapedText = Jsoup.clean(html, "",WHITE_LIST, settings);
                log.info("clean 处理结果: " + escapedText);
                // 3. 反转义
                return Entities.unescape(escapedText);
            }
        };
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("init XssConfig");
    }
}

